#include <jni.h>
#include <string>
#include "native-lib.h"

int user_id;

void sig_handler(int sino) {
    int status;
    //阻塞式函数
    LOGE("等待");
    wait(&status);
    LOGE("创建进程");
    create_child();
}

extern "C"
JNIEXPORT void JNICALL
Java_com_frank_1ghost_singleprocess_Watcher_createWatcher(JNIEnv *env, jobject instance,
                                                          jint userId) {
    user_id = userId;
    create_child();
}

void create_child() {
    pid_t pid = fork();
    if (pid < 0) {
        LOGE("pid<0,%d", pid);
    } else if (pid > 0) {
        LOGE("父进程 pid>0:%d", pid);
        //开启线程轮询
        child_start_monitor();
    } else {
        LOGE("子进程 pid:%d", pid);
        //开启线程轮询
        child_start_monitor();
    }
}

void *thread_rt(void *arg) {
    pid_t pid;
    while ((pid = getpid()) != 1) {
        sleep(2);
        LOGE("循环 ：%d", pid);
    }
    //父进程等于1 apk被干掉了
    LOGE("重启父进程");
    int i;
    i = execlp("am", "am", "startservice", "--user", user_id,
               "com.frank_ghost.singleprocess/com.frank_ghost.singleprocess.ProcessService",
               (char *) NULL);
    LOGE("重启父进程 i：%d", i);
    return ((void *) 0);
}

void child_start_monitor() {
    pthread_t tid;
    int i = 1;
    i = pthread_create(&tid, NULL, thread_rt, NULL);
    LOGE("返回值 i: %d", i);
}
